import Vue from 'vue'
import Vuex from 'vuex'
import httpRequest from '../script/httpRequest.js'
import config from '../script/config.js'

Vue.use(Vuex)

// 错误处理工具
const handleError = (error, defaultMessage = '操作失败') => {
	const message = error.response?.data?.message || error.message || defaultMessage;
	console.error('Store Error:', error);
	return Promise.reject(new Error(message));
};

// 重试请求工具
const retryRequest = async (requestFn, maxRetries = 3) => {
	for (let i = 0; i < maxRetries; i++) {
		try {
			return await requestFn();
		} catch (error) {
			if (i === maxRetries - 1) throw error;
			await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
		}
	}
};

const store = new Vuex.Store({
	state: {
		// 用户信息
		sender: null,
		
		// 智能咨询相关
		consultation: {
			list: [], // 咨询会话列表
			currentSession: null, // 当前咨询会话
			messages: [], // 当前会话的消息列表
			messagesMap: {}, // 所有会话的消息缓存
			aiModel: 'default' // AI模型类型
		},
		
		// 应用状态
		app: {
			isOnline: true,
			loading: false,
			scrollTop: 0
		}
	},
	
	mutations: {
		// 通用设置方法
		setPropName(state, { propName, value }) {
			// 支持嵌套属性设置，如 'consultation.list'
			const keys = propName.split('.');
			let target = state;
			
			for (let i = 0; i < keys.length - 1; i++) {
				target = target[keys[i]];
			}
			
			target[keys[keys.length - 1]] = value;
		},
		
		// 用户相关
		setUser(state, user) {
			state.sender = user;
			if (user) {
				// 确保对象被正确序列化为字符串进行存储
				uni.setStorageSync('sender', JSON.stringify(user));
			} else {
				uni.removeStorageSync('sender');
			}
		},
		
		// 咨询列表相关
		'consultation/setList'(state, list) {
			state.consultation.list = list;
			// 缓存到本地存储
			uni.setStorageSync('consultationList', JSON.stringify(list));
		},
		
		'consultation/addToList'(state, consultation) {
			const existingIndex = state.consultation.list.findIndex(c => c.id === consultation.id);
			if (existingIndex > -1) {
				state.consultation.list.splice(existingIndex, 1, consultation);
			} else {
				state.consultation.list.unshift(consultation);
			}
			// 更新本地存储
			uni.setStorageSync('consultationList', JSON.stringify(state.consultation.list));
		},
		
		'consultation/removeFromList'(state, consultationId) {
			const index = state.consultation.list.findIndex(c => c.id === consultationId);
			if (index > -1) {
				state.consultation.list.splice(index, 1);
				// 删除相关消息缓存
				delete state.consultation.messagesMap[consultationId];
				// 更新本地存储
				uni.setStorageSync('consultationList', JSON.stringify(state.consultation.list));
				uni.setStorageSync('consultationMessages', JSON.stringify(state.consultation.messagesMap));
			}
		},
		
		'consultation/updateLastMessage'(state, { consultationId, message, time }) {
			const consultation = state.consultation.list.find(c => c.id === consultationId);
			if (consultation) {
				consultation.lastMessage = message;
				consultation.lastTime = time || new Date().toISOString();
				// 更新本地存储
				uni.setStorageSync('consultationList', JSON.stringify(state.consultation.list));
			}
		},
		
		// 当前会话相关
		'consultation/setCurrentSession'(state, session) {
			state.consultation.currentSession = session;
		},
		
		// 消息相关
		'consultation/setMessages'(state, { consultationId, messages }) {
			// 规范化消息格式
			const normalizedMessages = messages.map(msg => ({
				...msg,
				id: msg.id || msg.Id || `msg-${Date.now()}-${Math.random()}`,
				SendId: Number(msg.SendId) || 0,
				State: typeof msg.State === 'number' ? msg.State : 1,
				CreateDateUtc: msg.CreateDateUtc || new Date().toISOString(),
				Content: msg.Content || '',
				Type: msg.Type || 0
			}));
			
			state.consultation.messages = normalizedMessages;
			state.consultation.messagesMap[consultationId] = normalizedMessages;
			
			// 更新本地存储
			uni.setStorageSync('consultationMessages', JSON.stringify(state.consultation.messagesMap));
		},
		
		'consultation/addMessage'(state, message) {
			const normalizedMessage = {
				...message,
				id: message.id || `msg-${Date.now()}-${Math.random()}`,
				SendId: Number(message.SendId) || 0,
				State: typeof message.State === 'number' ? message.State : 1,
				CreateDateUtc: message.CreateDateUtc || new Date().toISOString()
			};
			
			state.consultation.messages.push(normalizedMessage);
			
			// 更新消息缓存
			if (message.consultationId) {
				if (!state.consultation.messagesMap[message.consultationId]) {
					state.consultation.messagesMap[message.consultationId] = [];
				}
				state.consultation.messagesMap[message.consultationId].push(normalizedMessage);
				
				// 更新本地存储
				uni.setStorageSync('consultationMessages', JSON.stringify(state.consultation.messagesMap));
			}
		},
		
		'consultation/updateMessageState'(state, { messageId, state: messageState }) {
			// 更新当前消息列表中的消息状态
			const message = state.consultation.messages.find(m => m.id === messageId);
			if (message) {
				message.State = messageState;
			}
			
			// 更新缓存中的消息状态
			Object.keys(state.consultation.messagesMap).forEach(consultationId => {
				const cachedMessage = state.consultation.messagesMap[consultationId].find(m => m.id === messageId);
				if (cachedMessage) {
					cachedMessage.State = messageState;
				}
			});
			
			// 更新本地存储
			uni.setStorageSync('consultationMessages', JSON.stringify(state.consultation.messagesMap));
		},
		
		'consultation/updateMessageId'(state, { tempId, serverMessage }) {
			// 在当前消息列表中查找临时消息并更新
			const messageIndex = state.consultation.messages.findIndex(m => m.id === tempId);
			if (messageIndex > -1) {
				// 用服务器返回的消息替换临时消息
				state.consultation.messages.splice(messageIndex, 1, {
					...serverMessage,
					id: serverMessage.id || serverMessage.Id,
					SendId: Number(serverMessage.SendId) || 0,
					State: typeof serverMessage.State === 'number' ? serverMessage.State : 1,
					CreateDateUtc: serverMessage.CreateDateUtc || new Date().toISOString()
				});
			}
			
			// 在消息缓存中查找并更新
			Object.keys(state.consultation.messagesMap).forEach(consultationId => {
				const cachedMessageIndex = state.consultation.messagesMap[consultationId].findIndex(m => m.id === tempId);
				if (cachedMessageIndex > -1) {
					state.consultation.messagesMap[consultationId].splice(cachedMessageIndex, 1, {
						...serverMessage,
						id: serverMessage.id || serverMessage.Id,
						SendId: Number(serverMessage.SendId) || 0,
						State: typeof serverMessage.State === 'number' ? serverMessage.State : 1,
						CreateDateUtc: serverMessage.CreateDateUtc || new Date().toISOString()
					});
				}
			});
			
			// 更新本地存储
			uni.setStorageSync('consultationMessages', JSON.stringify(state.consultation.messagesMap));
		},
		
		// 应用状态相关
		'app/setOnlineStatus'(state, isOnline) {
			state.app.isOnline = isOnline;
		},
		
		'app/setLoading'(state, loading) {
			state.app.loading = loading;
		},
		
		'app/setScrollTop'(state, scrollTop) {
			state.app.scrollTop = scrollTop;
		}
	},
	
	actions: {
		// 初始化应用
		async initApp({ commit, dispatch }) {
			try {
				// 从本地存储恢复数据
				const sender = uni.getStorageSync('sender');
				if (sender) {
					commit('setUser', JSON.parse(sender));
				}
				
				const consultationList = uni.getStorageSync('consultationList');
				if (consultationList) {
					commit('consultation/setList', JSON.parse(consultationList));
				}
				
				const consultationMessages = uni.getStorageSync('consultationMessages');
				if (consultationMessages) {
					commit('setPropName', {
						propName: 'consultation.messagesMap',
						value: JSON.parse(consultationMessages)
					});
				}
				
			} catch (error) {
				console.error('初始化应用失败:', error);
			}
		},
		
		// 用户登出
		async logout({ commit }) {
			commit('setUser', null);
			commit('consultation/setList', []);
			commit('consultation/setMessages', { consultationId: '', messages: [] });
			commit('setPropName', { propName: 'consultation.messagesMap', value: {} });
			
			// 清除本地存储和token
			uni.removeStorageSync('sender');
			uni.removeStorageSync('token');
			uni.removeStorageSync('jwt');
			uni.removeStorageSync('consultationList');
			uni.removeStorageSync('consultationMessages');
		},
		
		// 获取咨询列表
		async 'consultation/fetchList'({ commit }, params = {}) {
			try {
				console.log('开始获取咨询列表...');
				const response = await retryRequest(() => 
					httpRequest.getConsultationList(config.APIURL, params)
				);
				
				console.log('咨询列表响应:', response);
				
				if (response.success) {
					// 适配新的分页响应格式
					const consultations = response.data?.consultations || response.data || [];
					console.log('解析的咨询列表:', consultations);
					commit('consultation/setList', consultations);
					return {
						consultations,
						pagination: {
							total: response.data?.total || 0,
							page: response.data?.page || 1,
							limit: response.data?.limit || 10,
							totalPages: response.data?.totalPages || 0
						}
					};
				} else {
					throw new Error(response.message || '获取咨询列表失败');
				}
			} catch (error) {
				console.error('获取咨询列表错误:', error);
				return handleError(error, '获取咨询列表失败');
			}
		},
		
		// 创建新咨询
		async 'consultation/create'({ commit }, consultationData = {}) {
			try {
				const response = await retryRequest(() => 
					httpRequest.createConsultation(config.APIURL, consultationData)
				);
				
				if (response.success) {
					const consultation = response.data;
					commit('consultation/addToList', consultation);
					return consultation;
				} else {
					throw new Error(response.message || '创建咨询失败');
				}
			} catch (error) {
				return handleError(error, '创建咨询失败');
			}
		},
		
		// 删除咨询
		async 'consultation/delete'({ commit }, consultationId) {
			try {
				const response = await retryRequest(() => 
					httpRequest.deleteConsultation(config.APIURL, consultationId)
				);
				
				if (response.success) {
					commit('consultation/removeFromList', consultationId);
					return response.data;
				} else {
					throw new Error(response.message || '删除咨询失败');
				}
			} catch (error) {
				return handleError(error, '删除咨询失败');
			}
		},
		
		// 获取咨询消息
		async 'consultation/fetchMessages'({ commit }, { consultationId, params = {} }) {
			try {
				const response = await retryRequest(() => 
					httpRequest.getConsultationMessages(config.APIURL, consultationId, params)
				);
				
				if (response.success) {
					// 适配新的分页响应格式
					const messages = response.data?.messages || response.data || [];
					commit('consultation/setMessages', {
						consultationId,
						messages
					});
					return {
						messages,
						pagination: {
							total: response.data?.total || 0,
							page: response.data?.page || 1,
							limit: response.data?.limit || 20,
							totalPages: response.data?.totalPages || 0
						}
					};
				} else {
					throw new Error(response.message || '获取消息失败');
				}
			} catch (error) {
				return handleError(error, '获取消息失败');
			}
		},
		
		// 发送咨询消息
		async 'consultation/sendMessage'({ commit, state }, { consultationId, content, type = 0 }) {
			try {
				const response = await retryRequest(() => 
					httpRequest.sendConsultationMessage(config.APIURL, {
						consultationId,
						content,
						type
					})
				);
				
				if (response.success) {
					// 更新最后消息
					commit('consultation/updateLastMessage', {
						consultationId,
						message: content,
						time: new Date().toISOString()
					});
					
					return response.data;
				} else {
					throw new Error(response.message || '发送消息失败');
				}
			} catch (error) {
				return handleError(error, '发送消息失败');
			}
		},
		
		// 标记消息已读
		async 'consultation/markRead'({ commit }, consultationId) {
			try {
				const response = await retryRequest(() => 
					httpRequest.markConsultationRead(config.APIURL, consultationId)
				);
				
				if (response.success) {
					return response.data;
				} else {
					throw new Error(response.message || '标记已读失败');
				}
			} catch (error) {
				return handleError(error, '标记已读失败');
			}
		},
		
		// 用户登录
		async login({ commit }, credentials) {
			try {
				// 前端验证
				if (!httpRequest.validateEmail(credentials.email)) {
					throw new Error('请输入有效的邮箱地址');
				}
				if (!httpRequest.validatePassword(credentials.password)) {
					throw new Error('密码必须包含字母和数字，长度6-20位');
				}
				
				const response = await retryRequest(() => 
					httpRequest.login(config.APIURL, credentials)
				);
				
				console.log('登录响应数据:', response);
				
				if (response.success) {
					const { token, user } = response.data;
					
					console.log('解析的登录数据:', { token: token ? '已获取' : '未获取', user });
					console.log('完整的User对象结构:', user); // <--- 添加这行日志
					
					// 保存token和用户信息
					uni.setStorageSync('token', token);
					commit('setUser', user);
					
					// 验证保存是否成功
					const savedToken = uni.getStorageSync('token');
					const savedUser = uni.getStorageSync('sender');
					console.log('保存验证:', { 
						savedToken: savedToken ? '已保存' : '未保存', 
						savedUser: savedUser ? '已保存' : '未保存' 
					});
					
					return user;
				} else {
					throw new Error(response.message || '登录失败');
				}
			} catch (error) {
				return handleError(error, '登录失败');
			}
		},
		
		// 用户注册
		async register({ commit }, userData) {
			try {
				// 前端验证
				if (!httpRequest.validateUsername(userData.username)) {
					throw new Error('用户名只能包含中文、字母、数字、下划线，长度2-20位');
				}
				if (!httpRequest.validateEmail(userData.email)) {
					throw new Error('请输入有效的邮箱地址');
				}
				if (!httpRequest.validatePassword(userData.password)) {
					throw new Error('密码必须包含字母和数字，长度6-20位');
				}
				
				const response = await retryRequest(() => 
					httpRequest.register(config.APIURL, userData)
				);
				
				if (response.success) {
					return response.data;
				} else {
					throw new Error(response.message || '注册失败');
				}
			} catch (error) {
				return handleError(error, '注册失败');
			}
		},
		
		// 发送验证码
		async sendVerificationCode({ commit }, email) {
			try {
				if (!httpRequest.validateEmail(email)) {
					throw new Error('请输入有效的邮箱地址');
				}
				
				const response = await retryRequest(() => 
					httpRequest.sendVerificationCode(config.APIURL, email)
				);
				
				if (response.success) {
					return response.data;
				} else {
					throw new Error(response.message || '发送验证码失败');
				}
			} catch (error) {
				return handleError(error, '发送验证码失败');
			}
		},
		
		// 验证验证码
		async verifyCode({ commit }, { email, code }) {
			try {
				if (!httpRequest.validateEmail(email)) {
					throw new Error('请输入有效的邮箱地址');
				}
				if (!code || code.length !== 6) {
					throw new Error('请输入6位验证码');
				}
				
				const response = await retryRequest(() => 
					httpRequest.verifyCode(config.APIURL, email, code)
				);
				
				if (response.success) {
					return response.data;
				} else {
					throw new Error(response.message || '验证码验证失败');
				}
			} catch (error) {
				return handleError(error, '验证码验证失败');
			}
		}
	},
	
	getters: {
		// 是否已登录
		isLoggedIn: state => !!state.sender,
		
		// 当前用户信息
		currentUser: state => state.sender,
		
		// 咨询列表
		consultationList: state => state.consultation.list,
		
		// 当前咨询会话
		currentConsultation: state => state.consultation.currentSession,
		
		// 当前消息列表
		currentMessages: state => state.consultation.messages,
		
		// 是否在线
		isOnline: state => state.app.isOnline,
		
		// 是否加载中
		isLoading: state => state.app.loading,
		
		// 未读消息总数
		totalUnreadCount: state => {
			return state.consultation.list.reduce((total, consultation) => {
				return total + (consultation.unreadCount || 0);
			}, 0);
		}
	}
});

export default store
